package com.yun.newBlog.blog.aspect;

import com.yun.newBlog.blog.annotation.LogPrinter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 定义一个切点，当方法定义中有LogPrinter注解时切入
     */
    @Pointcut("@annotation(com.yun.newBlog.blog.annotation.LogPrinter)")
    public void log() {
    }

    /**
     * 定义一个环形切面，并指定切点为log()，并可通过logPrinter参数获取注解中的参数type
     * @param proceedingJoinPoint
     * @param logPrinter
     * @return
     * @throws Throwable
     */
    @Around("log() && @annotation(logPrinter)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, LogPrinter logPrinter) throws Throwable{

        Object result;

        String type = logPrinter.type();

        String methodName = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();

        long start = System.currentTimeMillis();
        result = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();

        log.info("方法" + methodName + "执行耗时：" + (end-start) +"毫秒，type="+type);
        return result;
    }

}
